package com.hmdp.service.impl;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result getTypeList() {
        //首先查找redis里面有没有
        List<String> shopTypeJsonList=stringRedisTemplate.opsForList().range("cache:shopType:",0,-1);

        //如果查到了
        if(!shopTypeJsonList.isEmpty()){

            List<ShopType> shopTypeList=new ArrayList<>();
            for(String s:shopTypeJsonList){
                shopTypeList.add(JSONUtil.toBean(s,ShopType.class));
            }
            return Result.ok(shopTypeList);
        }

        List<ShopType> shopTypeList = query().orderByAsc("sort").list();
        if(shopTypeList==null){
            return Result.fail("店铺类型不存在");
        }

        //这边如果存在就写入缓存

        for(ShopType shopType:shopTypeList){
            stringRedisTemplate.opsForList().leftPush("cache:shopType:",JSONUtil.toJsonStr(shopType));
        }

        return Result.ok(shopTypeList);

    }
}
